<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *  Store Locator  Maitai Class
 *
 * 
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Google Maps
 * @author      Carla Missiona
 * @link
 */


class Debugstore {

    /**
     * Constructor
     *
     * @access    public
     */
    function __construct()
    {
        $this->CI =& get_instance();  
    }
    function locateStore( $city, $town, $brgy, $area ,$prov ,$locator, $region=false ){
      $markers = false;
      $this->CI->load->model('store');    
           
      $this->CI =& get_instance();       
        if($locator == "nearest"){  
           if( preg_match('/City/' , $city )== 1 ){
             //$city = $city." City";
           
          } 
          $r =  $this->checkLocation($city, $town, $brgy, $area);            
           //log_message("error", "CITY: " . $city . " -" . $r . "-asd ");
           //  log_message('error', 'Some variable did not contain a value.');
           if( $r == false ){    
          /* if location not in db */    
            $clientadd=""; $phil = "Philippines";
            /* compose clientadd  */  
            $i = 0;
            //foreach(array($phil,$prov,$city) as $k => $v ){   
            foreach(array($city,$prov,$phil) as $k => $v ){   
                log_message("error","param ".$v);
                $s = str_replace(' ', '%20', $v);
               // $s = $v;
                if(!empty($s)){                    
                   //$v = preg_replace('/\s+/', '', $v);
                   $clientadd.=$s;
                   if( $i <= 1){
                       $clientadd.="+"; 
                    }     
                 }
                 $i++;  
             } 
             
            /* fix for extra + */
            if(substr($clientadd,-1) ==="+"){
                $clientadd = substr_replace($clientadd, "", -1)  ;       
            } 

            //log_message("error", "CLIENTADD: " . $clientadd);
      
            $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$clientadd"; 
            echo $url."<br/>";
            //$url = urlencode($url);
            // log_message("error","url >> ".$url);   
             if(substr($url,-1) ==="+"){
                $url = substr($url,0,-1);                 
            } 
            
            $curl = curl_init();
            // call google to query lat long ng client address 
            curl_setopt_array($curl, array(
                    CURLOPT_RETURNTRANSFER => 1,
                    CURLOPT_URL => $url
            ));
          


               $resp = curl_exec($curl); print_r($resp,true);

               log_message("error", print_r($resp,true));
               curl_close($curl);
               /* curl 4 lat long */
               $google = json_decode($resp); 
               $gl = get_object_vars($google); // this convert object to array
               //log_message("error", "JSON RESPONSE: " . print_r($gl, true));
               echo" <br/>GL";     var_dump($gl); 
            
        $longname = $gl['results'][0]->address_components[0]->long_name;
        
             echo "<br/><br/>City";  
           if( $longname === "Pilipinas" || $longname === "Philippines"){ // if longname == Pilipinas mali
             echo "curl again";
             foreach(array($city,$prov,$phil) as $k => $v ){   
                log_message("error","param ".$v);
                $s = str_replace(' ', '', $v);
               // $s = $v;
                if(!empty($s)){                    
                   //$v = preg_replace('/\s+/', '', $v);
                   $clientadd.=$s;
                   if( $i <= 1){
                       $clientadd.="+"; 
                    }     
                 }
                 $i++;  
             } 
             
            /* fix for extra + */
            if(substr($clientadd,-1) ==="+"){
                $clientadd = substr_replace($clientadd, "", -1)  ;       
            } 

            //log_message("error", "CLIENTADD: " . $clientadd);      
            $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$clientadd";  echo "url 2".$url;

             if(substr($url,-1) ==="+"){
                $url = substr($url,0,-1);                 
            } 
            
            $curl = curl_init();
            // call google to query lat long ng client address 
            curl_setopt_array($curl, array(
                    CURLOPT_RETURNTRANSFER => 1,
                    CURLOPT_URL => $url
            ));
          


               $resp = curl_exec($curl); print_r($resp,true);

               log_message("error", print_r($resp,true));
               curl_close($curl);
               /* curl 4 lat long */
               $google = json_decode($resp); 
               $gl = get_object_vars($google); // this convert object to array
               //log_message("error", "JSON RESPONSE: " . print_r($gl, true));
               echo" <br/>GL";     var_dump($gl); 

               echo "<br/>end curl again<br/>";


          }// end curl again


         /* store in db */         
         $b = false; $lat=$gl['results'][0]->geometry->location->lat; $lng=$gl['results'][0]->geometry->location->lng ; // $lname=str_replace("+", " ", $clientadd);
         $a = array($lat, $lng,$city, $town, $brgy, $area); 
         foreach($a as $k => $v){ 
           /*  replacing spaces or empty with NULL  */
           if( $v == " " || empty($v) ){
            $a[$k] = NULL;    
           }
         } 
        
         while( $b == false ){ 
             //while error in db try repeat below          
            $b = $this->CI->map->putsClientLoc($a[0],$a[1],$a[2],$a[3],$a[4],$a[5]); // [0] = lat [1] = lng [2] = city etc corresponds to map model , and line 82
         }
         
          /* query nearest store */     
          // $markers = $this->CI->map->getNeareststore($lat,$lng,35); // moved
          // 10152014 change radius ->getStore(lat,lang,rad) to 15 from [ before  $markers = $this->CI->store->getStore($lat,$lng,30); ]
          $radius = 10;
          do{
                $markers = $this->CI->store->getStore($lat,$lng,$radius); 
                if(is_array($markers) || $markers != false ){
                    break;
                }
                $radius += 2; 
            }while(!$markers);
          
         //echo "markers = = >";var_dump($markers); echo "<br>";  
         if(isset($gl['results'][0]->geometry->location->lat)){ 
           //die(" format 1 ");
           $m = array();
           array_push($m, array( "Lat" => $gl['results'][0]->geometry->location->lat));
           array_push($m, array( "Lng" => $gl['results'][0]->geometry->location->lng));
           array_push($m, array( "stores" => $markers));
           array_push($m,"url".$clientadd);
            array_push($m,"citypoints".$lat."=".$lng);
           return $m;
           
           //return array( "Lat" => $gl['results'][0]->geometry->location->lat , "Lng" => $gl['results'][0]->geometry->location->lng , "stores" => $markers );
        }
        return " Error in user location input ";    
       } // end if not in db  
       else{  
           /*  if locations in db  call getNearest store  */  
           $n = array(); 
           foreach($r[0] as $k => $v){
              if($k == 'Lat' || $k == 'Lng' || $k == 'Longname'){
              array_push($n , array($k => $v ));
              }
           }   
          /* get markers or nearest stores */
              var_dump($r); echo "<br>";       
             $radius = 10; // increment by 50
             do{
                $markers = $this->CI->store->getStore($r[0]["Lat"],$r[0]["Lng"],$radius);   
                if(is_array($markers) || $markers != false ) {
                    break;
                }                           
                $radius += 2; 
              }while(!$markers);
              $n['stores'] = $markers;  
           return $n ;        
         }
   } // end locator nearest 
    else if($locator == "preferred"){
 
      $r = trim($region);         
      $response = $this->CI->store->getStore(false,false,false,$r) ;
      if( $response == false ){
          /* returns nothing */
      }
      else{       
          return $response;     
      }
       
    }
     
  }// end function get client Location 
 
    function checkLocation( $city, $town, $brgy, $area ){  
      $a = array($city, $town, $brgy, $area) ;
      foreach($a as $k => $v){ 
         /*  replacing spaces or empty with NULL  */
         if( $v == " " || empty($v) ){
          $a[$k] = NULL;    
         }
      } 
            
      return $this->CI->map->getClientLatlong($a[0], $a[1], $a[2], $a[3] ); 
    }
    
}

/* End of file Googlemap.php */
/* Location: ./application/libraries/Googlemap.php */